require 'logger'
require "gamifier/version"
require 'gamifier/errors'
require "multi_json"

module Gamifier
  class << self
    attr_writer :logger

    # Sets a configuration option. The keys will be symbolized.
    def set(key, opts = nil)
      if opts.nil?
        key.each do |k,v|
          config[k.to_sym] = v
        end
      else
        config[key.to_sym] = opts
      end
    end

    # Returns the configuration Hash.
    def config
      @config ||= {}
    end

    # Returns the global Engine. If you need multiple engine with
    # different API keys and/or URIs, you should create a new engine
    # directly with Gamifier::Engine.new
    def engine(&block)
      @engine ||= Engine.new
      block.call(@engine) if block
      @engine
    end

    # Creates and returns a new DSL::Network object. The given block
    # will be evaluated in the context of the network object.
    #
    # Usage:
    #
    #   network = Gamifier.dsl do
    #     site 'my-site' do
    #       set :url, 'my-site.com'
    #       ...
    #     end
    #   end
    def dsl(&block)
      network = DSL::Network.new
      DSL.eval_with_context(network, &block)
    end

    def logger
      @logger ||= begin
        l = Logger.new(STDERR)
        l.level = Logger::WARN
        l
      end
    end

    def reset!
      @engine = nil
      config.clear
    end

    def underscore(camel_cased_word)
      camel_cased_word.to_s.gsub(/::/, '/').
        gsub("Gamifier/", '').
        gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
        gsub(/([a-z\d])([A-Z])/,'\1_\2').
        tr("-", "_").
        downcase
    end
  end
end

require 'gamifier/engine'
require 'gamifier/dsl'
